package dao.impl;

import dao.BaseDao;
import dao.WalletDao;
import dao.WalletTypeDao;
import entity.Wallet;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class WalletDaoImpl extends BaseDao implements WalletDao {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;

    @Override
    public ResultSet selectWallet(int uid) {
        String sql = "SELECT * FROM wallettype wt,wallet w\n" +
                "WHERE wt.`wtid` = w.`wtid`\n" +
                "AND w.`uid` = ?;";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,uid);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public ResultSet selectWalletByWid(int wid) {
        String sql = "SELECT * FROM wallettype wt,wallet w\n" +
                "WHERE wt.`wtid` = w.`wtid`\n" +
                "AND w.`wid` = ?;";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,wid);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public int updateWallet(Wallet wallet) {
        int r = 0;
        String sql = "UPDATE wallet SET wamount = ?,wname = ?\n" +
                "WHERE wid = ?;";
        conn = getConnection();
        try{
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1,wallet.getWamount());
            pstmt.setString(2,wallet.getWname());
            pstmt.setInt(3,wallet.getWid());
            r = pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return r;
    }
}
